<template>
  <el-cascader
    ref="cascader"
    v-model="inputValue"
    v-bind="$attrs"
    v-on="$listeners"
  >
  </el-cascader>
</template>

<script>
import inputValueMixin from '@/mixins/inputValueMixin';
// 树结构递归获取选择值
function getLevelCheck(list, value, resultList = []) {
  let node = list.find(item => item.value === value);
  if (node) {
    resultList.push(node.value);
    return resultList;
  } else {
    for (let i = 0; i < list.length; i++) {
      const item = list[i];
      if (item.children) {
        const result = getLevelCheck(item.children, value, resultList);
        if(result) {
          resultList.push(item.value)
          return result;
        }
      }
    }
  }
}
export default {
  name: 'XmCascader',
  mixins: [inputValueMixin],
  props: {
    config: {
      type: Object,
      default: function () {
        return {}
      },
    },
  },
  data() {
    return {
    };
  },
  methods: {
    getChildSelected() {
      return this.inputValue.map(item => item[item.length - 1])
    },
    /**
     * 数据转换：['1:1','1:2'] 转为 [['1','1:1'],['1','1:2']]
     * 使用场景：存到后端的数据只有叶子节点，如['1:1','1:2']
     * 组件使用时所有层级数据，如[['1','1:1'],['1','1:2']]
     */
    setLevelCheckedFromChild() {
      if (this.$attrs.options && this.$attrs.options.length &&
          this.value && this.value.length && this.value.every(item => !(item instanceof Array))) {
          this.inputValue = this.value.map(item => {
            const checkeds = getLevelCheck(this.$attrs.options, item);
            return checkeds ? checkeds.reverse() : [];
          })
      }
    }
  },
  watch: {
    value(next) {
      if (this.config && this.config.needLevelCheck) {
        this.setLevelCheckedFromChild()
      }
    },
  },
  created() {
    if (this.config && this.config.needLevelCheck) {
      this.setLevelCheckedFromChild()
    }
  }
};
</script>

<style scoped lang="scss">
</style>
